<?php

namespace app\api\controller\god;


use app\common\controller\Api;
use app\common\model\Readorder as ReadorderModel;

/**
 * 报读订单
 */
class ReadOrder extends Api
{
    protected $noNeedRight = '*'; // 所有接口都不需要进行授权操作

    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Readorder');
    }

    public function add()
    {
        if (!$this->request->isPost()) {
            $this->error('请求方式错误');
            return;
        }
        $res = [];
        try {
            $args = $this->request->param();
            $args['user_id'] = $this->auth->id;
            $this->checkArgs($args);
            // 检查是否已报读
            $checkOrder = ReadorderModel::checkOrder($args);
            if (!empty($checkOrder)) {
                $res = [
                    'order_id' => $checkOrder['id'],
                    'order_no' => $checkOrder['order_no'],
                    'pay_price' => bcdiv(intval($checkOrder['pay_price']), 100, 2),
                ];
                throw new \Exception('您已报读此专业，不能再报读', -2);
            }
            // 报读类型
            $enrollment = \app\common\model\Enrollment::get(['id' => $args['enrollment_id'], 'status' => 'normal']);
            if (empty($enrollment)) {
                throw new \Exception('报读类型数据不存在', -1);
            }
            // 年级
            $grade = \app\common\model\Collegegrade::get(['id' => $args['grade_id'], 'status' => 'normal']);
            if (empty($grade)) {
                throw new \Exception('报读的年级数据不存在', -1);
            }
            // 报读层次
            $readLevel = \app\common\model\Stureadlevelinfo::get(['id' => $args['read_level_id'], 'status' => 'normal']);
            if (empty($readLevel)) {
                throw new \Exception('读取层次数据不存在', -1);
            }
            // 院校
            $college = \app\common\model\College::get(['id' => $args['college_id'], 'status' => 'normal']);
            if (empty($college)) {
                throw new \Exception('报读院校不存在', -1);
            }
            // 专业
            $major = \app\common\model\Major::get(['id' => $args['major_id'], 'college_id' => $args['college_id'], 'status' => 'normal']);
            if (empty($major)) {
                throw new \Exception('报读院校的专业不存在', -1);
            }
            // 考区
            $examarea = \app\common\model\Examarea::get(['id' => $args['exam_area_id'], 'status' => 'normal']);
            if (empty($examarea)) {
                throw new \Exception('考区不存在', -1);
            }
            // 生成订单数据
            $args['order_no'] = "R" . date("YmdHis") . mt_rand(10, 9999); // 订单
            $args['total_price'] = intval($major['read_price']);  // 总价格,单位分
            $args['pay_price'] = intval($major['read_price']);  // 需求支付价格,单位分
            $args['submit_time'] = time(); // 下单时间
            $args['ip'] = request()->ip();; // 下单IP
            $saveRes = ReadorderModel::create([
                'user_id' => $args['user_id'],
                'order_no' => $args['order_no'],
                'enrollment_id' => $args['enrollment_id'],
                'grade_id' => $args['grade_id'],
                'read_level_id' => $args['read_level_id'],
                'college_id' => $args['college_id'],
                'major_id' => $args['major_id'],
                'exam_area_id' => $args['exam_area_id'],
                'total_price' => $args['total_price'],
                'pay_price' => $args['pay_price'],
                'wxconfig' => '',
            ]);
            if (empty($saveRes)) {
                throw new \Exception('创建订单失败', -1);
            }
            $res = [
                'order_id' => $saveRes->id,
                'order_no' => $args['order_no'],
                'pay_price' => bcdiv($args['pay_price'], 100, 2),
            ];

        } catch (\Exception $e) {
            if ($e->getCode() === -1) {
                $this->error($e->getMessage());
                return;
            } else if ($e->getCode() === -2) {
                $this->success('已有未支付订单，请支付', $res);
                return;
            }
            $this->error('服务异常，请稍后重试！');
            return;
        }
        $this->success('下单成功，请支付', $res);
    }

    /**
     * @throws \Exception
     */
    private function checkArgs($args)
    {
        if (empty($args['user_id'])) {
            throw new \Exception('请登陆后操作', -1);
        }
        if (empty($args['enrollment_id'])) {
            throw new \Exception('报读类型参数异常', -1);
        }
        if (empty($args['grade_id'])) {
            throw new \Exception('年级参数异常', -1);
        }
        if (empty($args['read_level_id'])) {
            throw new \Exception('报读层次参数异常', -1);
        }
        if (empty($args['college_id'])) {
            throw new \Exception('院校参数异常', -1);
        }
        if (empty($args['major_id'])) {
            throw new \Exception('专业参数异常', -1);
        }
        if (empty($args['exam_area_id'])) {
            throw new \Exception('考试县区参数异常', -1);
        }
    }

    // 列表
    public function lists()
    {
        try {
            $userId = $this->auth->id;
            $mod = new ReadorderModel();
            $list = $mod::all([
                'user_id' => $userId,
                'status' => 'normal'
            ]);
            if (!empty($list)) {
                $enrollmentIdList = array_unique(array_column($list, 'enrollment_id'));
                $gradeIdList = array_unique(array_column($list, 'grade_id'));
                $read_levelIdList = array_unique(array_column($list, 'read_level_id'));
                $collegeIdList = array_unique(array_column($list, 'college_id'));
                $majorIdList = array_unique(array_column($list, 'major_id'));
                $exam_areaIdList = array_unique(array_column($list, 'exam_area_id'));

                $enrollments = \app\common\model\Enrollment::where(['id' => ['in', $enrollmentIdList]])->column('name', 'id');
                $grade = \app\common\model\Collegegrade::where(['id' => ['in', $gradeIdList]])->column('name', 'id');
                $readLevel = \app\common\model\Stureadlevelinfo::where(['id' => ['in', $read_levelIdList]])->column('name', 'id');
                $college = \app\common\model\College::where(['id' => ['in', $collegeIdList]])->column('co_name', 'id');
                $major = \app\common\model\Major::where(['id' => ['in', $majorIdList]])->column('name', 'id');
                $examArea = \app\common\model\Examarea::where(['id' => ['in', $exam_areaIdList]])->column('name', 'id');

                foreach ($list as $k => $item) {
                    $item['enrollment_id_text'] = ($enrollments[$item['enrollment_id']]) ?? '';
                    $item['grade_id_text'] = ($grade[$item['grade_id']]) ?? '';
                    $item['read_level_id_text'] = ($readLevel[$item['read_level_id']]) ?? '';
                    $item['college_id_text'] = ($college[$item['college_id']]) ?? '';
                    $item['major_id_text'] = ($major[$item['major_id']]) ?? '';
                    $item['exam_area_id_text'] = ($examArea[$item['exam_area_id']]) ?? '';

                    $item['pay_type_text'] = ReadorderModel::getPayTypeText($item['pay_type']);
                    $item['pay_status_text'] = ReadorderModel::getStatusText($item['pay_status']);

                    $list[$k] = $item;
                }
            }
        } catch (\Exception $e) {
            if ($e->getCode() === -1) {
                $this->error($e->getMessage());
                return;
            }
            $this->error('服务异常，请稍后重试！');
            return;
        }
        $this->success('下单成功，请支付', $list);
    }
}